package ca.uwaterloo.titslongcall;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;


//Known Bugs till 9:32pm, Feb 11:
//NumberOfMyContacts() & numberofmycallcards() don't work as desired: always return 1.
//note: remember that when numberofmycontacts() is zero, app crashes.
//Bug solved on 3:10 pm, Feb 12. Referred to http://stackoverflow.com/questions/12528836/shared-preferences-only-saved-first-time! Yeah!
public class MainActivity extends Activity {
	int contactrequest = 0;
	int callcardrequest = 1;
	
	public class CallCard {
		String Pre, PIN;
		public CallCard (String Pre, String PIN){	//constructor
			this.Pre = Pre+",,1,"; 	//Pre is the prefix of the callcard, say 18669138555;
			this.PIN = PIN; 	//PIN is the PIN of the card.
		}
	}

	public class Contact {
		String Name, Phone;
		public Contact(String Name, String Phone){ //constructor
			this.Name = Name;
			this.Phone = Phone;
		}
	}

	public class SPMethods{
		//We Have 4 SharedPreferences: AllofMyContacts, SetofMyContacts, AllofMyCallCards, SetofMyCallCards.
		String SetofMyContacts = "SetofMyContacts";
		String SetofMyCallCards = "SetofMyCallCards";
		String AllofMyContacts = "AllofMyContacts";
		String AllofMyCallCards = "AllofMyCallCards";
		String Name_Set = "Name_Set";
		String Card_Set = "Card_Set";
		String MyDefaultCallCard = "MyDefaultCallCard";
		String DefaultCC = "DefaultCC";
		

		@SuppressLint("NewApi")
		public void saveSharedPreferences(String SPName, String Key, String Value){
			
			SharedPreferences MySP = getSharedPreferences(SPName, MODE_PRIVATE);
			SharedPreferences.Editor editor = MySP.edit();
			
			if (SPName == SetofMyContacts){	//when i wanna edit the set of my contact...(it's for counting)
				Set<String> MySet = MySP.getStringSet(Name_Set, new TreeSet<String>());	//in this set, contacts are stored as name+phone
				Set<String> MyNewSet =  new TreeSet<String>();
				for (String each: MySet){
					MyNewSet.add(each);
				}
				MyNewSet.add(Key+Value);
				editor.putStringSet(Name_Set, MyNewSet);
				editor.commit();
			}
			
			if (SPName == SetofMyCallCards){	//when i wanna edit the set of my callcard...same
				Set<String> MySet = MySP.getStringSet(Card_Set, new TreeSet<String>());
				Set<String> MyNewSet =  new TreeSet<String>();
				for (String each: MySet){
					MyNewSet.add(each);
				}
				MyNewSet.add(Key+Value);
				editor.putStringSet(Card_Set, MyNewSet);
				editor.commit();
			}
			
			if (SPName == AllofMyContacts || SPName == AllofMyCallCards){	//when i wanna add a contact or a callcard
				editor.putString(Key+Value, Key+Value);
				editor.commit();
			}
			
			if (SPName == MyDefaultCallCard){
				editor.putString(DefaultCC, Key+Value);
				editor.commit();
			}
		}
		
		@SuppressLint("NewApi")
		public void removeContact(String ContactInfo){
			SharedPreferences MySP1 = getSharedPreferences(SetofMyContacts, MODE_PRIVATE);
			SharedPreferences.Editor editor1 = MySP1.edit();
			Set<String> myset = loadSharedPreferencesSet(SetofMyContacts, Name_Set);
			Set<String> mynewset = new TreeSet<String>();
			for (String each: myset){
				mynewset.add(each);
			}
			mynewset.remove(ContactInfo);
			editor1.putStringSet(Name_Set, mynewset);
			SharedPreferences MySP2 = getSharedPreferences(AllofMyContacts, MODE_PRIVATE);
			SharedPreferences.Editor editor2 = MySP2.edit();
			editor2.remove(ContactInfo);
			editor1.commit();
			editor2.commit();
		}
		
		@SuppressLint("NewApi")
		public void removeCallCard(String CallCardInfo){
			SharedPreferences MySP1 = getSharedPreferences(SetofMyCallCards, MODE_PRIVATE);
			SharedPreferences.Editor editor1 = MySP1.edit();
			Set<String> myset = loadSharedPreferencesSet(SetofMyCallCards, Card_Set);
			Set<String> mynewset = new TreeSet<String>();
			for (String each: myset){
				mynewset.add(each);
			}
			mynewset.remove(CallCardInfo);
			editor1.putStringSet(Card_Set, mynewset);
			SharedPreferences MySP2 = getSharedPreferences(AllofMyCallCards, MODE_PRIVATE);
			SharedPreferences.Editor editor2 = MySP2.edit();
			editor2.remove(CallCardInfo);
			editor1.commit();
			editor2.commit();
		}
		
		public String loadSharedPreferences(String SPName,String Key){
			SharedPreferences MySP = getSharedPreferences(SPName, MODE_PRIVATE);
			return MySP.getString(Key, "");
		}
		
		@SuppressLint("NewApi")
		public Set<String> loadSharedPreferencesSet(String SPName, String Key){
			SharedPreferences MySP = getSharedPreferences(SPName, MODE_PRIVATE);
			return MySP.getStringSet(Key, new TreeSet<String>());
		}
		
		
		public void addContact(Contact contact){
			saveSharedPreferences(AllofMyContacts, contact.Name, contact.Phone);
			saveSharedPreferences(SetofMyContacts, contact.Name, contact.Phone); //this line might be bugged!
		}
		
		public void addCallCard(CallCard callcard){
			saveSharedPreferences(AllofMyCallCards, callcard.Pre, callcard.PIN);
			saveSharedPreferences(SetofMyCallCards, callcard.Pre, callcard.PIN);
		}
		
		public void setDefaultCallCard(CallCard callcard){
			saveSharedPreferences(MyDefaultCallCard, callcard.Pre, callcard.PIN);
		}
		
		public int NumberofMyContacts(){
			return Arrays.asList(loadSharedPreferencesSet(SetofMyContacts,Name_Set).toArray()).size();    //could be bugs
		}
		
		public int NumberofMyCallCards(){
			return Arrays.asList(loadSharedPreferencesSet(SetofMyCallCards,Card_Set).toArray()).size();
		}
		
		public Button presentAsButtons(int i, String type){
			Button button = new Button(getApplicationContext());
			if (type == SetofMyContacts){
				List namelist = Arrays.asList(loadSharedPreferencesSet(SetofMyContacts,Name_Set).toArray());
				String name = loadSharedPreferences(AllofMyContacts, (String) namelist.get(i));
				name = name.replaceAll("\\d+", "");
				button.setText(name);
			}
			if (type == SetofMyCallCards){
				List cardlist = Arrays.asList(loadSharedPreferencesSet(SetofMyCallCards,Card_Set).toArray());
				String card = loadSharedPreferences(AllofMyCallCards, (String) cardlist.get(i));
				card = card.replaceAll("\\d+", "");
				button.setText(card);
			}
			return button;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		final SPMethods spm = new SPMethods();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		LinearLayout mainlayout = (LinearLayout) findViewById(R.id.mainlayout);
		mainlayout.setOrientation(LinearLayout.VERTICAL);
		Button addcontact = (Button) findViewById(R.id.button1);
		addcontact.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, ContactActivity.class);
				startActivityForResult(intent, contactrequest);
			}
		});
		
		Button addcallcard = (Button) findViewById(R.id.button2);
		addcallcard.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, CallCardActivity.class);
				startActivityForResult(intent, callcardrequest);
			}
		});
		TextView instruction = new TextView(getApplicationContext());
		instruction.setText("To refresh your contact list, simply rotate your screen:)");
		mainlayout.addView(instruction);		
		
		for (int i=0; i<spm.NumberofMyContacts(); i++){
			Button button = spm.presentAsButtons(i, spm.SetofMyContacts);
			mainlayout.addView(button);
			List namelist = Arrays.asList(spm.loadSharedPreferencesSet(spm.SetofMyContacts,spm.Name_Set).toArray());
			final String name = spm.loadSharedPreferences(spm.AllofMyContacts, (String) namelist.get(i));
			button.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent tonext = new Intent(MainActivity.this, PickCardActivity.class);
					tonext.putExtra("Info", name);
					startActivity(tonext);
				}
			});
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		SPMethods spm = new SPMethods();
		if (requestCode == contactrequest && resultCode == RESULT_OK){
			if (data.hasExtra("contactName")&&data.hasExtra("contactPhone")){
				String Name = data.getExtras().getString("contactName");
				String Phone = data.getExtras().getString("contactPhone");
				Contact newcontact = new Contact(Name, Phone);
				spm.addContact(newcontact);
			}
		}
		else if (requestCode == callcardrequest && resultCode == RESULT_OK){
			if (data.hasExtra("cardPre")&&data.hasExtra("cardPin")){
				String Pre = data.getExtras().getString("cardPre");
				String PIN = data.getExtras().getString("cardPin");
				CallCard newcallcard  = new CallCard(Pre, PIN);
				spm.addCallCard(newcallcard);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
